package com.ruoyi.commission.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.attached.domain.Attached;
import com.ruoyi.attached.service.IAttachedService;
import com.ruoyi.attachedData.domain.AttachedData;
import com.ruoyi.attachedData.service.IAttachedDataService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.engineering.domain.Engineering;
import com.ruoyi.engineering.service.IEngineeringService;
import com.ruoyi.enterprise.domain.Enterprise;
import com.ruoyi.enterprise.service.IEnterpriseService;
import com.ruoyi.notice.domain.Notice;
import com.ruoyi.notice.service.INoticeService;
import com.ruoyi.report.domain.Report;
import com.ruoyi.report.service.IReportService;
import com.ruoyi.sample.domain.Sample;
import com.ruoyi.sample.service.ISampleService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.task.domain.Task;
import com.ruoyi.task.service.ITaskService;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.commission.mapper.CommissionMapper;
import com.ruoyi.commission.domain.Commission;
import com.ruoyi.commission.service.ICommissionService;

/**
 * 委托Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-08
 */
@Service
public class CommissionServiceImpl implements ICommissionService
{
    @Autowired
    private CommissionMapper commissionMapper;

    @Autowired
    private ISampleService sampleService;

    @Autowired
    private IAttachedService attachedService;

    @Autowired
    private IAttachedDataService attachedDataService;

    @Autowired
    private IReportService reportService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private ICommissionService commissionService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IEngineeringService engineeringService;

    @Autowired
    private IEnterpriseService enterpriseService;

    /**
     * 查询委托
     *
     * @param id 委托主键
     * @return 委托
     */
    @Override
    public Commission selectCommissionById(Long id)
    {
        return commissionMapper.selectCommissionById(id);
    }

    @Override
    public List<Commission> selectCommissionListAll(Commission commission){
        List<Commission> list = commissionMapper.selectCommissionListAll(commission);
        return list;
    }


    @Override
    public List<Commission> selectCommissionListCount(Commission commission)
    {
        List<Commission> list = commissionMapper.selectCommissionListCount(commission);

        return list;
    }

    /**
     * 查询委托列表
     *
     * @param commission 委托
     * @return 委托
     */
    @Override
    public List<Commission> selectCommissionList(Commission commission)
    {
        List<Commission> list = commissionMapper.selectCommissionList(commission);

        for (Commission item : list){
            //检测项目列表(室内)
            Sample sample = new Sample();
            sample.setCommissionId(item.getId());
            List<Sample> sampleList = sampleService.selectSampleList(sample);
            item.setSampleList(sampleList);

            //附表列表
            Attached attached = new Attached();
            attached.setCommissionId(item.getId());
            List<Attached> attachedList = attachedService.selectAttachedList(attached);
            item.setAttachedList(attachedList);
            //检测报告列表
            Report report = new Report();
            report.setCommissionId(item.getId());
            List<Report> reportList = reportService.selectReportListCount(report);
            item.setReportList(reportList);

            //检测项目（室外）
            AttachedData attachedData = new AttachedData();
            attachedData.setCommissionId(item.getId());
            List<AttachedData> attachedDataList = attachedDataService.selectAttachedDataList(attachedData);

            item.setAttachedDataList(attachedDataList);
        }

        return list;
    }

    /**
     * 新增委托
     *
     * @param commission 委托
     * @return 结果
     */
    @Override
    public int insertCommission(Commission commission)
    {
        commission.setCreateTime(DateUtils.getNowDate());
        Engineering engineeringOne = engineeringService.selectEngineeringById(commission.getEngineeringId());
        Enterprise enterpriseOne = enterpriseService.selectEnterpriseById(engineeringOne.getEnterpriseId());

        commission.setEnterpriseId(engineeringOne.getEnterpriseId());
        commission.setEnterpriseName(enterpriseOne.getName());
        Integer isCommission = commissionMapper.insertCommission(commission);
        Long id = commission.getId();

        //如果有adIds 就 存入
        if(commission.getAdIds() != null){
            String[] idsArr = commission.getAdIds().split(",");
            if(idsArr != null && idsArr.length > 0){
                for(String itemid : idsArr){
                    AttachedData attachedData = new AttachedData();
                    attachedData.setId(Long.valueOf(itemid));
                    attachedData.setCommissionId(id);
                    attachedDataService.updateAttachedData(attachedData);
                }
            }
        }

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR); // 获取当前年份
        int month = calendar.get(Calendar.MONTH) + 1; // 获取当前月份（需要加1，因为月份从0开始）
        String number = "WT"+year+month+id;

        Commission commission2 = new Commission();
        commission2.setId(id);
        commission2.setNumber(number);
        commissionService.updateCommission(commission2);

        return isCommission;
    }

    /**
     * 修改委托
     *
     * @param commission 委托
     * @return 结果
     */
    @Override
    public int updateCommission(Commission commission)
    {
        commission.setUpdateTime(DateUtils.getNowDate());

        Map desc = getInputPathAndOutputPath();
        String inputPath = desc.get("inputPath").toString();
        String outputPath = desc.get("outputPath").toString();
        String savePath = desc.get("savePath").toString();

        commissionService.createExcel(commission.getId(),inputPath,outputPath,savePath);
        return commissionMapper.updateCommission(commission);
    }

    public  Map<String, String> getInputPathAndOutputPath(){
        HashMap<String, String> map = new HashMap<>();
        // 上传文件路径
        String uploadPath = RuoYiConfig.getUploadPath();
        String inputPath = uploadPath+"/weituomuban.xlsx";//空白模版地址
        String outputPath = uploadPath+"/commission";
        createDir(outputPath);
        String fileName = generateRandomFileName()+".xlsx";
        outputPath = outputPath+"/" + fileName;

        String savePath = "/upload/commission/"+fileName;

        map.put("inputPath",inputPath);
        map.put("outputPath",outputPath);
        map.put("savePath",savePath);

        return map;
    }

    public static String createDir(String outputPath) {
        // 创建Path对象
        Path path = Paths.get(outputPath);

        // 检查文件夹是否存在
        if (!Files.exists(path)) {
            try {
                // 如果不存在，创建文件夹
                Files.createDirectories(path);
                System.out.println("文件夹已创建: " + outputPath);
            } catch (IOException e) {
                System.err.println("创建文件夹失败: " + e.getMessage());
            }
        } else {
            System.out.println("文件夹已存在: " + outputPath);
        }
        return outputPath;
    }


    public static String generateRandomFileName() {
        Random random = new Random();
        int randomInt = random.nextInt(1000000); // 生成随机数
        long currentTime = new Date().getTime(); // 获取当前时间戳
        String fileName = Long.toString(currentTime) + String.valueOf(randomInt);
        return fileName;
    }

    /**
     * 批量删除委托
     *
     * @param ids 需要删除的委托主键
     * @return 结果
     */
    @Override
    public int deleteCommissionByIds(Long[] ids)
    {
        return commissionMapper.deleteCommissionByIds(ids);
    }


    /**
     * 批量逻辑删除委托
     *
     * @param ids 需要删除的委托主键
     * @return 结果
     */
    @Override
    public int logicDeleteCommission(Long[] ids,String delType,Long delUser)
    {
        return commissionMapper.logicDeleteCommission(ids,delType,delUser);
    }

    /**
     * 删除委托信息
     *
     * @param id 委托主键
     * @return 结果
     */
    @Override
    public int deleteCommissionById(Long id)
    {
        return commissionMapper.deleteCommissionById(id);
    }

    @Override
    public Map<String, Object> getDetectionContent(Long commissionId, String businessType){
        HashMap<String, Object> map = new HashMap<>();
        JSONObject sJson = new JSONObject();
        JSONObject Json = new JSONObject();
        String detection_content_str = "";
        String project_str = "";
        if("shinei".equals(businessType)){
            System.out.println("shineijinlai");
            List<SysDictData> dictDataList = dictTypeService.selectDictDataByType("detection_item_indoor");

            //所有室内检测
            Sample sample = new Sample();
            sample.setCommissionId(commissionId);
            List<Sample> sampleList = sampleService.selectSampleList(sample);
            Integer i = 0;
            for (Sample sample1 : sampleList) {
                for(SysDictData dictData : dictDataList) {
                    if(sample1.getProject().equals(dictData.getDictValue())){
                        if(dictData.getRemark() != null) {
                            detection_content_str += dictData.getRemark() + ",";
                        }
//                        if( StringUtils.isNotEmpty(dictData.getRemark())) {
//                            String[] idsArr = dictData.getRemark().split(",");
//                            sJson.put(sample1.getProject(), idsArr);
//                        }else{
//                            sJson.put(sample1.getProject(), "");
//                        }
                    }
                }

                project_str+= sample1.getProjectName()+"("+sample1.getNumber()+"),";
//                String s = "{'project':'"+sample1.getProjectName()+"','number':"+sample1.getNumber()+"}";
//                String i_str = String.valueOf(i);
//                Json.put(i_str,s);
                i++;
            }
        }

        if("shiwai".equals(businessType)){
            System.out.println("shiwaijinlai");
            List<SysDictData> dictDataList = dictTypeService.selectDictDataByType("detection_item_scene");
            //所有室外检测
            AttachedData attachedData = new AttachedData();
            attachedData.setCommissionId(commissionId);
            List<AttachedData> attachedDataList = attachedDataService.selectAttachedDataList(attachedData);
            Integer i = 0;
            for (AttachedData itemAttachedData : attachedDataList) {
                for(SysDictData dictData : dictDataList) {
                    if (itemAttachedData.getTestMethod().equals(dictData.getDictLabel())){
                        if(dictData.getRemark() != null) {
                            detection_content_str += dictData.getRemark() + ",";
                        }
//                        if( StringUtils.isNotEmpty(dictData.getRemark())) {
//                            String[] idsArr = dictData.getRemark().split(",");
//                            sJson.put(dictData.getDictValue(), idsArr);
//                        }else{
//                            sJson.put(dictData.getDictValue(), "");
//                        }
                    }
                }

                project_str+= itemAttachedData.getTestMethod()+",";
//                String s = "{'project':'"+itemAttachedData.getTestMethod()+"'}";
//                String i_str = String.valueOf(i);
//                Json.put(i_str,s);
                i++;
            }
        }

//        String jsonString = sJson.toString();
        map.put("detection_content",sJson);
//        map.put("jiance",Json);
//        map.put("businessType",businessType);
//        if (detection_content_str.endsWith(",")) {
//            detection_content_str = detection_content_str.substring(0, detection_content_str.length() - 1);
//        }
        map.put("detection_content_str",detection_content_str);
//        if (project_str.endsWith(",")) {
//            project_str = project_str.substring(0, project_str.length() - 1);
//        }
        map.put("project_str",project_str);

        return map;
    }


    //生成excel表格
    @Override
    public String createExcel(Long commissionId,String inputPath, String outputPath,String savePath){
        try {
            Commission commissionOne = commissionMapper.selectCommissionById(commissionId);
//            System.out.println("jjjj");
//            System.out.println(commissionOne);
            HashMap<String, String> map = new HashMap<>();
            map.put("tableCode",commissionOne.getTableCode());
            map.put("number",commissionOne.getNumber());
            map.put("enterpriseName",commissionOne.getEnterpriseName());
            map.put("userName",commissionOne.getUserName());
            map.put("mobile",commissionOne.getMobile());
            map.put("engineeringName",commissionOne.getEngineeringName());
            map.put("address",commissionOne.getAddress());//工程地点
            map.put("constructionUnit",commissionOne.getConstructionUnit());//建设单位
            map.put("supervisionUnit",commissionOne.getSupervisionUnit());//监理单位
            map.put("designUnit",commissionOne.getDesignUnit());//设计单位
            map.put("surveyUnit",commissionOne.getSurveyUnit());//勘察单位
            map.put("construcUnit",commissionOne.getConstrucUnit());//施工单位
            map.put("overview",commissionOne.getOverview());//工程概况
            map.put("detectionContent",commissionOne.getDetectionContent());//检测内容
            map.put("accordingContent",commissionOne.getAccordingContent());//依据内容
            map.put("businessManagerName",commissionOne.getBusinessManagerName());//业务受理员

            if(commissionOne.getCommissionDate() != null) {
                // 创建SimpleDateFormat对象，指定想要的日期格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                // 调用format()方法将Date对象转换为字符串
                String dateString = sdf.format(commissionOne.getCommissionDate());
                map.put("commissionDate", dateString);//委托日期
            }else{
                map.put("commissionDate", "");//委托日期
            }
            Commission commission = new Commission();
            commission.setId(commissionId);
            commission.setWordFile(savePath);
            commissionMapper.updateCommission(commission);

            Workbook workbook = ExcelUtil.readExcelFile(inputPath);
            ExcelUtil.modifyExcelContent(workbook,map);
            ExcelUtil.writeExcelFile(workbook,outputPath );
        } catch (IOException  e) {
            e.printStackTrace(); // 处理异常情况
        } finally {
            // 可选：关闭workbook以释放资源，但writeExcelFile中已处理关闭操作，此处可省略。
        }
        return "success";
    }

    @Override
    public String updateDone(Long commissionId){
        Commission commissionOne =  commissionService.selectCommissionById(commissionId);
        if("jcdone".equals(commissionOne.getStatus())){
            return "此委托单已完结，请不要重复提交";
        }

        if("shinei".equals(commissionOne.getBusinessType())){
            Sample sample = new Sample();
            sample.setCommissionId(commissionId);
            sample.setStatus(2L);
            List<Sample> SampleListAll = sampleService.selectSampleList(sample);//所有试验项目

            if(SampleListAll.size() == 0){
                return "此委托单没有试验项目，无法完结";
            }

            Sample sample2 = new Sample();
            sample2.setCommissionId(commissionId);
            sample2.setStatus(2L);
            sample2.setIsDone(2L);
            List<Sample> SampleListDone= sampleService.selectSampleList(sample2);//已完成试验项目

            Integer SampleListAllNum = SampleListAll.size();
            Integer SampleListDoneNum = SampleListDone.size();
            System.out.println("sdone");
            System.out.println(SampleListDoneNum);
            System.out.println(SampleListAllNum);
            //已完成试验项目 小于 所有试验项目
            if(SampleListDoneNum < SampleListAllNum){
                return "还有未完成的试验项目，无法完结";
            }
        }

        if("shiwai".equals(commissionOne.getBusinessType())){
            AttachedData attachedData = new AttachedData();
            attachedData.setCommissionId(commissionId);
            attachedData.setStatus(2L);
            List<AttachedData> attachedDataListAll = attachedDataService.selectAttachedDataList(attachedData);//所有试验项目

            if(attachedDataListAll.size() == 0){
                return "此委托单没有试验项目，无法完结";
            }

            AttachedData attachedData2 = new AttachedData();
            attachedData2.setCommissionId(commissionId);
            attachedData2.setStatus(2L);
            attachedData2.setIsDone(2L);
            List<AttachedData> attachedDataListDone = attachedDataService.selectAttachedDataList(attachedData2);//已完成试验项目

            Integer attachedDataListAllNum = attachedDataListAll.size();
            Integer attachedDataListDoneNum = attachedDataListDone.size();

            //已完成试验项目 小于 所有试验项目
            if(attachedDataListDoneNum < attachedDataListAllNum){
                return "还有未完成的试验项目，无法完结";
            }
        }
        Commission commission2 = new Commission();
        commission2.setId(commissionId);
        commission2.setStatus("jcdone");
        commissionService.updateCommission(commission2);

        //任务 所有试验项目完成之后-通知项目经理 上传报告
        Task task = new Task();
        task.setCommissionId(commissionId);
        task.setEngineeringId(commissionOne.getEngineeringId());
        task.setTaskType("报告上传");
        task.setStatus("0");
        task.setTaskContent(commissionOne.getEngineeringName() + "的委托单" + commissionOne.getNumber() +"所有试验项目已完成，请及时上传报告。");
        task.setChargePerson(commissionOne.getBusinessManagerId().toString());
        taskService.insertTask(task);

        return "委托单已完成";
    }

    @Override
    public int acceptance(Commission commission){
        commission.setStatus("souli");
        //改变试验表的状态
        Commission commissionOne = commissionService.selectCommissionById(commission.getId());
        if("shinei".equals( commissionOne.getBusinessType() ) ){
            sampleService.updateSampleForStatus(commission.getId());
        }
        if("shiwai".equals( commissionOne.getBusinessType() ) ){
            attachedDataService.updateAttachedDataForStatus(commission.getId());
        }

        //任务生成一条 改变之前一条任务状态
        Task task = new Task();
        task.setCommissionId(commissionOne.getId());
        task.setEngineeringId(commissionOne.getEngineeringId());
        task.setTaskType("分配试验项目");
        task.setStatus("0");
        task.setTaskContent( commissionOne.getEngineeringName() + "的委托单" + commissionOne.getNumber() +
                "已受理，请及时分配。");
        task.setChargePerson(commission.getBusinessManagerId().toString());
        taskService.insertTask(task);

        Task task1 = new Task();
        task1.setTaskType("委托受理");
        task1.setCommissionId(commissionOne.getId());
        List<Task> taskList = taskService.selectTaskList(task1);

        if(taskList.size() > 0) {
            task1.setId(taskList.get(0).getId());
            task1.setStatus("1");
            task1.setExecuteTime(DateUtils.getNowDate());
            taskService.updateTask(task1);
        }

        //消息 受理通知 给 委托单位项目员
        Notice notice = new Notice();
        notice.setCommissionId(commissionOne.getId());
        notice.setEngineeringId(commissionOne.getEngineeringId());
        notice.setNoticType("受理通知");
        notice.setNoticContent(commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+"已受理！");
        notice.setUserId(commission.getBusinessManagerId().toString());
        noticeService.insertNotice(notice);

        int is_res = commissionService.updateCommission(commission);

        //生成 excel 表格
        Map desc = commissionService.getInputPathAndOutputPath();
        String inputPath = desc.get("inputPath").toString();
        String outputPath = desc.get("outputPath").toString();
        String savePath = desc.get("savePath").toString();
        commissionService.createExcel(commission.getId(),inputPath,outputPath,savePath);

        return is_res;
    }
}
